﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using Microsoft.Phone;

namespace TM.QWeibo.Client.Helper
{
    public static class ImageHelper
    {
        /// <summary>
        /// 压缩图片，只调整质量，不调整分辨率
        /// </summary>
        /// <param name="soucre">图片流</param>
        /// <param name="quality">质量1-100</param>
        public static Stream Compression(Stream soucre)
        {
            var quality = AppSetting.ImageQuality;
            soucre.Seek(0, SeekOrigin.Begin);
            var p = quality / 100.0;
            var writeableBitmap = PictureDecoder.DecodeJpeg(soucre);
            var width = writeableBitmap.PixelWidth*p;
            var height = writeableBitmap.PixelHeight*p;
            var outstream = new MemoryStream();
            writeableBitmap.SaveJpeg(outstream, (int)width, (int)height, 0, quality);
            outstream.Seek(0, SeekOrigin.Begin);
            return outstream;
        }

        public static void IsGif(string url,Action<bool> callback) {
            if (string.IsNullOrWhiteSpace(url) || callback == null) {
                return;
            }
            var request = (HttpWebRequest)WebRequest.Create(url + "/2000");
            request.AllowReadStreamBuffering = true;
            request.Method = "get";
            request.BeginGetResponse((asynchronousResult) =>
            {
                var request2 = (HttpWebRequest)asynchronousResult.AsyncState;
                var response = (HttpWebResponse)request2.EndGetResponse(asynchronousResult);
                bool b = string.Equals(response.ContentType, "image/gif", StringComparison.CurrentCultureIgnoreCase);
                response.Close();
                if (callback != null)
                {
                    callback(b);
                }
            }, request);
        }
    }
}
